package com.ambercrm.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.ambercrm.common.Common;
import com.ambercrm.constant.Constant;
import com.ambercrm.tools.LogUtils;
import com.ambercrm.tools.SharedPreferencesHelper;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.tencent.smtt.sdk.QbSdk;
import com.yanzhenjie.kalle.KalleConfig;
import com.yanzhenjie.kalle.connect.http.RedirectInterceptor;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import cn.jpush.android.api.JPushInterface;

public class MyApplication extends Application {
    static MyApplication instance = null;
    public static MyApplication getApplicationInstance() {
        return instance;
    }

    DisplayImageOptions mOptions;
    DisplayImageOptions mRoundOptions;
    ImageLoader mImageLoader = null;
    ImageLoader mRoundImageLoader = null;
    ImageLoadingListener mAnimateFirstListener = null;
    SharedPreferencesHelper sp = null;
    @Override
    public void onCreate() {
        super.onCreate();
        String processName = getProcessName(this, android.os.Process.myPid());
        if (!processName.equals(getPackageName(this))) {
            // 如果是主进程则初始化
            return;
        }

        sp = new SharedPreferencesHelper(this);
        if (sp.getValue(Constant.sp_Token) != null) {
            Common.getInstance().setToken(sp.getValue(Constant.sp_Token));
        }

        instance = this;
        initImageLoader();

        // 初始化x5webview
        initX5WebView();

        JPushInterface.setDebugMode(true); 	// 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);     		// 初始化 JPush

        initKalle();
    }

    // 初始化Kalle
    private void initKalle() {
        KalleConfig.newBuilder()
                .addInterceptor(new RedirectInterceptor())
                .build();
    }

    private void initX5WebView(){
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                LogUtils.showLog("-----------X5浏览器内核初始化状态：" + arg0);
            }

            @Override
            public void onCoreInitFinished() {
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(),  cb);
    }

    private void initImageLoader() {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                // 设置内存缓存大小
                .threadPriority(Thread.NORM_PRIORITY)
                // 设置线程优先级
                .diskCacheSize(200 * 1024 * 1024).memoryCacheSize(500 * 1024 * 1024)
                .denyCacheImageMultipleSizesInMemory().threadPoolSize(4).tasksProcessingOrder(QueueProcessingType.LIFO)
                .memoryCache(new WeakMemoryCache()).memoryCacheSizePercentage(60)
                .build();

        mImageLoader = ImageLoader.getInstance();
        mImageLoader.init(config);

        mRoundImageLoader = ImageLoader.getInstance();
        mRoundImageLoader.init(config);

        mRoundOptions = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(8)) // 设置成圆角图片
                .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
                .cacheInMemory(true).imageScaleType(ImageScaleType.EXACTLY).build();

        mOptions = new DisplayImageOptions.Builder().cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
                .cacheInMemory(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565).build();

        mAnimateFirstListener = new AnimateFirstDisplayListener();
    }

    private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

        static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

    // 显示图片
    public void displayImg(String url, ImageView imgV) {
        try {
            mImageLoader.displayImage(url, imgV, mOptions, mAnimateFirstListener);
        } catch (Exception e) {

        }
    }

    // 显示圆角图片
    public void displayRoundImg(String url, ImageView imgV) {
        try {
            mRoundImageLoader.displayImage(url, imgV, mRoundOptions, mAnimateFirstListener);
        } catch (Exception e) {

        }
    }

    // 显示圆角图片
    public void displayRoundImgPixel(String url, ImageView imgV, int roundPixel) {
        try {
            mRoundOptions = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(roundPixel)) // 设置成圆角图片
                    .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
                    .cacheInMemory(true).imageScaleType(ImageScaleType.EXACTLY).build();
            mRoundImageLoader.displayImage(url, imgV, mRoundOptions, mAnimateFirstListener);
        } catch (Exception e) {

        }
    }

    public Bitmap loadImage(String url) {
        return mImageLoader.loadImageSync(url, mOptions);
    }

    // 清除内存缓存
    public void clearMomeryCache(String imgUrl) {
        try {
            mImageLoader.getMemoryCache().remove(imgUrl);
            mImageLoader.getMemoryCache().get(imgUrl).recycle();
        } catch (Exception e) {

        }
    }

    // 清除单张图片的内存以及sdcard存储
    public void clearSingleImageCache(String url) {
        clearMomeryCache(url);
        mImageLoader.getDiskCache().remove(url);
    }

    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    public String getPackageName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void mIUISetStatusBarLightMode(Activity activity, boolean dark) {
        Window window = activity.getWindow();
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && isMiUIV7OrAbove()) {
                    //开发版 7.7.13 及以后版本采用了系统API，旧方法无效但不会报错，所以两个方式都要加上
                    if (dark) {
                        activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    } else {
                        activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                    }
                }
            } catch (Exception e) {

            }
        }
    }

    private boolean isMiUIV7OrAbove() {
        try {
            final Properties properties = new Properties();
            properties.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
            String uiCode = properties.getProperty("ro.miui.ui.version.code", null);
            if (uiCode != null) {
                int code = Integer.parseInt(uiCode);
                return code >= 5;
            } else {
                return false;
            }

        } catch (final Exception e) {
            return false;
        }

    }

    public static boolean setFlymeLightStatusBar(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }
}
